import { type AxiosPromise } from "axios";
import { get, post } from "@/utils/request";
import { useMutation, useQueryClient } from "@tanstack/react-query";

export const ruleKeys = {
  all: () => ["rules"],
  rulesTableTree: () => ["rulesTableTree"],
  rulesSelectTree: () => ["rulesSelectTree"],
};
// 权限列表
export const rules = (): AxiosPromise => {
  return get("/rules?format=select&limit=9999", {});
};
// 权限树形结构（表格使用）
export const rulesTableTree = (): AxiosPromise => {
  return get("/rules?format=table_tree&limit=9999", {});
};
// 权限树形结构（下拉框使用）
export const rulesSelectTree = (): AxiosPromise => {
  return get("/rules?format=tree&limit=9999&type=0,1", {});
};

export interface RuleData {
  [key: string]: unknown;
}

export const ruleAdd = (data: RuleData): AxiosPromise => {
  return post("/rules", data);
};
export const ruleAEdit = (data: RuleData): AxiosPromise => {
  return post("/rules/update", data);
};
export const ruleADel = (data: RuleData): AxiosPromise => {
  return post("/rules/delete", data);
};

export function useRuleAdd() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (newData: RuleData) => {
      return ruleAdd(newData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ruleKeys.rulesTableTree() });
    },
  });
}

export function useRuleEdit() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: RuleData) => {
      return ruleAEdit(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ruleKeys.rulesTableTree() });
    },
  });
}

export function useRuleDel() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: RuleData) => {
      return ruleADel(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ruleKeys.rulesTableTree() });
    },
  });
}
